package ordersubmit

import (
	// "fmt"
	"strconv"
	"strings"

	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/lib/shoppingcart"
	"mall/service/order/rpc/orderclient"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

// CartDelHandler 清理购物车handler
type CartDelHandler struct {
	// 合成复用Next
	Next
}

// Do 清理购物车的逻辑
func (h *CartDelHandler) Do(c *Context) (err error) {
	if !c.Resp.StockValid || !c.Resp.AddressValid || !c.Resp.BalanceValid || !c.Resp.PromotionValid ||
		!c.Resp.ActivityValid || !c.Resp.CouponValid || !c.Resp.FinalValid {
		return
	}

	// logx.Infow("清理购物车...")

	var skuIds []string
	for _, v := range c.Resp.List {
		// 不是兑换商品和随手兑一件商品
		if len(v.ExchangeLogIds) == 0 && v.ExchangeGoodsId == nil && v.SkuId != nil && v.Quantity != nil && *v.SkuId > 0 && *v.Quantity > 0 {
			skuIds = append(skuIds, strconv.FormatInt(int64(*v.SkuId), 10))
		}
	}
	if len(skuIds) > 0 {
		shoppingCart := shoppingcart.NewShoppingCart(c.Ctx, c.SvcCtx, "forum:cart")
		_, err = shoppingCart.BatchDelete(strconv.FormatUint(c.UserId, 10), skuIds)
		if err != nil {
			logx.Errorw("CartDelHandler BatchDelete err", logx.Field("detail", err.Error()))
			// logrus.Info(fmt.Sprintf("CartDelHandler BatchDelete err: %+v", err))
		}

		_, err = c.SvcCtx.OrderRpc.DeleteShoppingCart(c.Ctx, &orderclient.DeleteShoppingCartReq{
			UserId: pointy.GetPointer(uint64(c.UserId)),
			SkuIds: pointy.GetPointer(strings.Join(skuIds, ",")),
		})
		if err != nil {
			logx.Errorw("CartDelHandler DeleteCartItem err", logx.Field("detail", err.Error()))
			// logrus.Info(fmt.Sprintf("CartDelHandler DeleteCartItem err: %+v", err))
		}
	}

	return
}
